#include <stdlib.h>
#include <assert.h>
#include <opencv/highgui.h>

#include "yuv.h"

#include <stdbool.h> // WBS


// read only YUV 420P (8 bits)

int
main(int argc, char **argv)
{
    int width;
    int height;
    bool display = true; // WBS: se true = RGB, se false = gray; default: true
    FILE *fin = NULL;
    struct YUV_Capture cap;
    enum YUV_ReturnValue ret;
    IplImage *bgr;

    IplImage* framegray; // WBS

    if (argc != 5)
    {
        fprintf(stderr, "usage: %s file.yuv width height display\n", argv[0]);
        return 1;
    }
    width = atoi(argv[2]);
    height = atoi(argv[3]);
    display = atoi(argv[4]); // WBS
    
    if (width <= 0 || height <= 0)
    {
        fprintf(stderr, "error: bad frame dimensions: %d x %d\n", width, height);
        return 1;
    }
    fin = fopen(argv[1], "rb");
    if (!fin)
    {
        fprintf(stderr, "error: unable to open file: %s\n", argv[1]);
        return 1;
    }
    ret = YUV_init(fin, width, height, &cap);
    assert(ret == YUV_OK);


    bgr = cvCreateImage(cvSize(width,height), IPL_DEPTH_8U, 3);
    assert(bgr);
    framegray = cvCreateImage(cvSize(width,height), IPL_DEPTH_8U, 1); 
    assert(framegray); 

    

    for (; ;) // loop for read frame by frame
    {
        ret = YUV_read(&cap);
	
      cvCvtColor(cap.ycrcb, bgr, CV_YCrCb2BGR); // ycbcr to BRG
      cvNamedWindow(argv[1], CV_WINDOW_AUTOSIZE);

	
        if (ret == YUV_EOF)
        {
            cvWaitKey(1); // (1) close after play; (0) not close
            break;
        }
        else if (ret == YUV_IO_ERROR)
        {
            fprintf(stderr, "I/O error\n");
            break;
        }


      if ( display ) 
      {        
	cvShowImage(argv[1], bgr);
        cvWaitKey(33); // ms; 1s / 30 fps = 33.33 
      } 
      else 
      {
	cvCvtColor(bgr, framegray, CV_BGR2GRAY);    
	cvShowImage(argv[1], framegray); 		
	cvWaitKey(33);
      }
      
      
      
    }
    
    
    cvDestroyWindow(argv[1]); // WBS  
    
    return 0;
}
